package com.huishu.order.component;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName：OrderMessageSender
 * @Author: ljj
 * @Date: 2023/4/13 17:24
 */
@Component
@Slf4j
public class OrderMessageSender {

    //@Value("${rocketmq.huishu.scheduleTopic}")
    private String scheduleTopic;

    // @Value("${rocketmq.huishu.asyncOrderTopic}")
    private String asyncOrderTopic;

    private String ORDERTAG = "create-order";

    private String UPDATE_ORDERTAG = "update-order";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送延时订单
     * delayTimeLevel代表延迟级别  messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     *
     * @param orderSn 订单sn
     * @return
     */
    public boolean sendTimeOutOrderMessage(String orderSn) {
        Message message = MessageBuilder.withPayload(orderSn)
                .setHeader(RocketMQHeaders.KEYS, orderSn)
                .build();
        SendResult result = rocketMQTemplate.syncSend("schedule-message-topic" + ":" + "sync-tags", message, 5000, 15);
        return SendStatus.SEND_OK == result.getSendStatus();
    }

    /**
     * 发送订单消息
     *
     * @return
     */
    public boolean sendCreateOrderMsg(String outTradeNo) {
        SendResult result = rocketMQTemplate.syncSend("async-order-topic" + ":" + ORDERTAG, outTradeNo);
        return SendStatus.SEND_OK == result.getSendStatus();
    }

    /**
     * 发送修改订单状态，扣减db库存订单消息
     *
     * @return
     */
    public boolean sendUpdateOrderMsg(Map<String, String> map) {
        SendResult result = rocketMQTemplate.syncSend("async-order-topic" + ":" + UPDATE_ORDERTAG, JSON.toJSONString(map));
        return SendStatus.SEND_OK == result.getSendStatus();
    }
}
